const express = require("express");
const User = require("../model/user");
const Login = require("../middleware/login");

// 创建登陆应用
const loginApp = express();

// 登陆
loginApp.post("/", (req, res, next) => {
  let { username, password } = req.body;
  User.login(username, password)
    .then((result) => {
      if (result.length != 0) {
        req.session.user = result;
        req.user = result;
        res.send({
          status: 1,
          info: "登陆成功",
          result,
        });
      } else {
        res.json({
          state: 1,
          info: "用户或密码错误",
        });
      }
    })
    .catch((err) => {
      next(err);
    });
});
// 用户列表
loginApp.get("/userlist", [Login.UserList], (req, res, next) => {
  res.json({
    userList:req.userList,
    total:req.total
  });
});
// 删除用户
loginApp.post("/delUser", [Login.delUser], (req, res) => {
  if (req.affectedRows > 0) {
    res.json({
      code: 1,
      msg: "删除成功",
    });
  } else {
    res.json({
      code: 0,
      msg: "删除失败",
    });
  }
});
// 用户添加
loginApp.post("/userAdd", [Login.userAdd], (req, res) => {
  if (req.insertId) {
    res.json({
      code: 1,
      msg: "添加成功",
    });
  } else {
    res.json({
      code: 0,
      msg: "添加失败",
    });
  }
});
// 编辑用户信息
loginApp.post("/editUser", [Login.editUser], (req, res) => {
  if (req.affectedRows > 0) {
    res.json({
      code: 1,
      msg: "用户编辑成功",
    });
  } else {
    res.json({
      code: 0,
      msg: "用户编辑失败",
    });
  }
});
module.exports = loginApp;
